import * as fs from "fs"
import * as path from "path"

export class DirectoryDeleter {
  /**
   * 删除只读文件
   */
  private removeReadonly(filePath: string): boolean {
    try {
      // 检查文件是否存在
      if (!fs.existsSync(filePath)) {
        return true
      }

      const stats = fs.statSync(filePath)
      
      // 如果是只读文件，移除只读属性
      if (!(stats.mode & 0o200)) {
        console.log(`移除只读属性: ${filePath}`)
        fs.chmodSync(filePath, 0o666)
      }

      // 删除文件
      fs.unlinkSync(filePath)
      return true
    } catch (error) {
      console.error(`删除文件失败: ${filePath}`, error)
      return false
    }
  }

  /**
   * 递归收集所有文件和目录
   */
  private collectPaths(dirPath: string): { files: string[]; dirs: string[] } {
    const files: string[] = []
    const dirs: string[] = []

    const collectRecursive = (currentPath: string) => {
      try {
        if (!fs.existsSync(currentPath)) {
          return
        }

        const entries = fs.readdirSync(currentPath, { withFileTypes: true })

        for (const entry of entries) {
          const fullPath = path.join(currentPath, entry.name)

          if (entry.isDirectory()) {
            collectRecursive(fullPath)
            dirs.push(fullPath)
          } else {
            files.push(fullPath)
          }
        }
      } catch (error) {
        console.error(`收集路径失败: ${currentPath}`, error)
      }
    }

    collectRecursive(dirPath)
    return { files, dirs }
  }

  /**
   * 强制删除目录
   */
  async deleteDirectory(dirPath: string): Promise<boolean> {
    console.log("=== DirectoryDeleter.deleteDirectory 开始 ===")
    console.log("目标目录:", dirPath)

    try {
      // 检查目录是否存在
      if (!fs.existsSync(dirPath)) {
        console.log("目录不存在，跳过删除")
        return true
      }

      const failedOperations: string[] = []

      // 首先尝试一次性删除整个目录树
      try {
        fs.rmSync(dirPath, { recursive: true, force: true })
        console.log("成功删除目录")
        return true
      } catch (error) {
        console.log("批量删除失败，使用逐个删除方式...", error)
      }

      // 如果批量删除失败，尝试逐个文件删除
      const { files, dirs } = this.collectPaths(dirPath)

      console.log(`找到 ${files.length} 个文件, ${dirs.length} 个目录`)

      // 先删除文件
      for (const file of files) {
        if (!this.removeReadonly(file)) {
          failedOperations.push(`文件: ${file}`)
        }
      }

      // 按深度排序目录（深度优先删除）
      dirs.sort((a, b) => {
        const depthA = a.split(path.sep).length
        const depthB = b.split(path.sep).length
        return depthB - depthA // 反向排序，深度大的先删
      })

      // 删除目录
      for (const dir of dirs) {
        try {
          if (fs.existsSync(dir)) {
            fs.rmdirSync(dir)
          }
        } catch (error) {
          failedOperations.push(`目录: ${dir} - ${error}`)
        }
      }

      // 最后尝试删除根目录
      try {
        if (fs.existsSync(dirPath)) {
          fs.rmdirSync(dirPath)
        }
      } catch (error) {
        failedOperations.push(`根目录: ${dirPath} - ${error}`)
      }

      if (failedOperations.length > 0) {
        console.log("部分删除操作失败:")
        failedOperations.forEach(op => console.log(`  ${op}`))
      }

      console.log("=== 目录删除完成 ===")
      return true
    } catch (error) {
      console.error("=== 删除目录失败 ===")
      console.error("错误详情:", error)
      throw error
    }
  }
}

